#!/usr/bin/python
# Copyright 2007 Alex K (wtwf.com) All rights reserved.
# $Id: expandRss.py,v 1.35 2009-01-07 21:27:56 ark Exp $

"""output csv for a mysql statement
-d mysql_defaults_file
-e sql expression
-o output filename [optional]
"""

import sys
import os
import logging
import getopt
import csv
import MySQLdb
import MySQLdb.cursors

if sys.version_info < (2, 4):
  raise Exception("You probably need python 2.5 or greater")

def usage(code, msg=''):
  if code:
    fd = sys.stderr
  else:
    fd = sys.stdout
  print >> fd, __doc__ % dict(PROGRAM=os.path.basename(sys.argv[0]))
  if msg:
    print >> fd, msg
  sys.exit(code)


def Main(argv):
  logging.basicConfig()
  logging.getLogger().setLevel(logging.INFO)
  try:
    opts, args = getopt.getopt(argv[1:], 'hvqd:e:o:',
                               ['help', 'vebose', 'quiet',
                                'default_file=', 'expression=', 'output=',
                                'noheader'])
  except getopt.error, msg:
    usage(1, msg)

  if args:
    usage(1)

  output = None
  expression = None
  default_file = None
  header = True
  for opt, arg in opts:
    if opt in ('-h', '--help'):
      usage(0)
    if opt in ('-v', '--verbose'):
      logging.getLogger().setLevel(logging.DEBUG)
    if opt in ('-q', '--quiet'):
      logging.getLogger().setLevel(logging.WARNING)
    if opt in ('-d', '--default_file'):
      default_file = arg
    if opt in ('-e', '--expression'):
      expression = arg
    if opt in ('-o', '--output'):
      output = arg
    if opt == '--noheader':
      header = False

  if default_file is None:
    usage(3, msg="You must provide a mysql defaults_file with -d")
  if expression is None:
    usage(4, msg="You must provide an SQL statement with -e")

  logging.info("using default_file: %s", default_file)
  con = MySQLdb.connect(read_default_file=default_file,
                        cursorclass=MySQLdb.cursors.SSCursor)
  cur = con.cursor()

  logging.info("SQL: %s", expression)

  if output:
    output_stream = open(output, 'w')
  else:
    output_stream = sys.stdout

  csv_out = csv.writer(output_stream)

  cur.execute(expression)

  # First the header
  if header:
    csv_out.writerow([x[0] for x in cur.description])
  # now the data
  for line in cur:
    csv_out.writerow(line)


if __name__ == '__main__':
  Main(sys.argv)
